package com.hjm.java.service;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.hjm.java.sql.HJMHelper;
import com.hjm.java.utils.HjmFailCallBack;
import com.hjm.java.utils.HjmGlideUtil;
import com.hjm.java.utils.HjmObjectCallBack;
import com.hjm.java.utils.HjmSuccessCallBack;
import com.hjm.ui.comment.entity.Comment;

import java.util.ArrayList;
import java.util.List;

public class CommentService extends BaseService {
    private static final String TAG = "CommentService";
    List<Comment> commentList;

    public CommentService(Context mContext, Handler mHandler) {
        super(mContext, mHandler);
    }

    public void getCommentList(String id, HjmSuccessCallBack successCallBack, HjmFailCallBack failCallBack) {
        httpUtils.getList(baseUrl + "/comment/goods?id=" + id, Comment.class, (isSuccess, t, message) -> {
            if (isSuccess) {
                HjmGlideUtil.UrlToBitmap(mContext, baseImgUrl,
                        t.stream().map(Comment -> String.valueOf(Comment.getUserPic())).toArray(String[]::new),
                        HJMHelper.getInstance(mContext),
                        (position, bitmap) -> {
                            t.get(position).setUserPicBitmap(bitmap);
                        },
                        () -> {
                            commentList = t;
                            mHandler.post(() -> {
                                successCallBack.onSuccess();
                            });
                        });
            } else {
                Log.d(TAG, "getCommentList: 获取失败 " + message);
                this.commentList = new ArrayList<>();
                mHandler.post(() -> {
                    failCallBack.onFail(message);
                });
            }
        });
    }

    public void newComment(Comment comment, HjmSuccessCallBack successCallBack, HjmFailCallBack failCallBack) {
        httpUtils.postByToken(baseUrl + "/comment/new", comment, String.class, (HjmObjectCallBack<String>) (isSuccess, string, msg) -> {
            mHandler.post(() -> {
                if (isSuccess) {
                    successCallBack.onSuccess();
                } else {
                    failCallBack.onFail(msg);
                }
            });
        });
    }

    public List<Comment> getCommentList() {
        return commentList;
    }
}
